using System;
using System.ComponentModel;
using System.Globalization;
using Framework.Library.Core.Utils.Reflection;

namespace Framework.Library.Core.Utils.Converters
{
    public class DotNetTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof (string))
                return true;

            return base.CanConvertFrom(context, sourceType);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof (string))
                return true;

            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string)
                return Type.GetType((string) value, true, false);

            return base.ConvertFrom(context, culture, value);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,
                                         Type destinationType)
        {
            if (destinationType == typeof (string))
            {
                if (value != null)
                    return ReflectionUtils.GetNameAndAssessmblyName((Type) value);
                else
                    return string.Empty;
            }

            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}